package Product;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import entity.Product;
@WebServlet("/Product.ProductServlet")
public class ProductServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProductDao productDao = new ProductDao();
        ArrayList<HashMap<String, String>> productsList = productDao.connectToDatabase();
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("[");
        for (int i = 0; i < productsList.size(); i++) {
            HashMap<String, String> productMap = productsList.get(i);
            jsonBuilder.append("{");
            jsonBuilder.append("\"pid\":").append("\"").append(productMap.get("pid")).append("\",");
            jsonBuilder.append("\"name\":").append("\"").append(productMap.get("name")).append("\",");
            jsonBuilder.append("\"description\":").append("\"").append(productMap.get("description")).append("\",");
            jsonBuilder.append("\"image\":").append("\"").append(productMap.get("image")).append("\",");
            jsonBuilder.append("\"price\":").append("\"").append(productMap.get("price")).append("\"");
            jsonBuilder.append("}");
            if (i < productsList.size() - 1) {
                jsonBuilder.append(",");
            }
        }
        jsonBuilder.append("]");
        String json = jsonBuilder.toString();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        ProductDao productDao = new ProductDao();

        if ("add".equals(action)) {
            HashMap<String,String> user =  (HashMap<String, String>) request.getSession().getAttribute("user");
            if(user==null){
                request.getRequestDispatcher("login.jsp").forward(request,response);
                return;
            }
            int userId = Integer.parseInt(user.get("userId"));// 从会话中获取用户ID
            String productName = request.getParameter("productName");
            String productDescription = request.getParameter("productDescription");
            double price = Double.parseDouble(request.getParameter("price"));
            String image = request.getParameter("image");
            int stockQuantity = Integer.parseInt(request.getParameter("stockQuantity"));

            Product product = new Product(0, userId, productName, productDescription, price, stockQuantity);
            product.setImage(image);

            productDao.addProduct(product);
        } else if ("delete".equals(action)) {
            // 删除商品
            int productId = Integer.parseInt(request.getParameter("productId"));
            productDao.deleteProduct(productId);
        }else if ("favorites".equals(action)) {
            HashMap<String,String> user =  (HashMap<String, String>) request.getSession().getAttribute("user");
            if(user==null){
                request.getRequestDispatcher("login.jsp").forward(request,response);
                return;
            }
            int userId = Integer.parseInt(user.get("userId"));// 从会话中获取用户ID
            List<HashMap<String, String>> favorites = null;
            try {
                favorites = productDao.getFavoritesByUserId(userId);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            request.setAttribute("favorites", favorites);
            System.out.println(favorites);
            request.getRequestDispatcher("/force").forward(request, response);
        }
    }
}